package com.swx.generate.filter;

import com.alibaba.fastjson.JSON;
import com.swx.generate.bean.ApiResult;
import com.swx.generate.util.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Ricky
 * @date 2020/12/17
 */
@Slf4j
public class ReauestLogFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;

        String uri = request.getRequestURI();
        String method = request.getMethod();
        String ip = request.getRemoteAddr();


        long startTime = System.currentTimeMillis();
        try {
            chain.doFilter(req, res);
        } catch (Exception e) {
            String errMsg = ExceptionUtil.getMessage(e);
            log.error("过滤器捕获到错误：{}", errMsg, e);

            res.setContentType("application/json;charset=utf-8");
            PrintWriter toClient = res.getWriter();
            toClient.write(JSON.toJSONString(ApiResult.fail(errMsg)));
            toClient.close();
        } finally {
            log.info("<==\t{}\t{}\t{}\t{}", ip, method, uri, System.currentTimeMillis() - startTime);
        }
    }

    @Override
    public void destroy() {

    }
}
